package com.study.common.utils;

import cn.dev33.satoken.stp.StpUtil;
import com.study.common.enums.UserType;
import com.study.common.helper.LoginHelper;
import com.study.common.utils.spring.SpringUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.LocaleUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * 获取i18n资源文件
 *
 * @author Lion Li
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class MessageUtils {

    private static final MessageSource MESSAGE_SOURCE = SpringUtils.getBean(MessageSource.class);
    private static final String CONTENT_LANGUAGE = "language";
    private static final String DEFAULT_LANGUAGE="zh_CN";

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        boolean isLogin = StpUtil.isLogin();
        if (isLogin) {
            UserType userType = UserType.getUserType(StpUtil.getLoginId().toString());
            String languageIden;
            switch (userType) {
                case SYS_USER:
                    languageIden = LoginHelper.getLoginUser().getLanguage();
                    break;
                case APP_USER:
                    String contentLanguage = ServletUtils.getRequest().getHeader(CONTENT_LANGUAGE);
                    if (StringUtils.isNotBlank(contentLanguage)) {
                        languageIden = contentLanguage;
                    } else {
                        languageIden = DEFAULT_LANGUAGE;
//                        languageIden = AppLoginHelper.getLoginUser().getLanguageIden();
                    }
                    break;
                default:
                    String language = ServletUtils.getRequest().getHeader(CONTENT_LANGUAGE);
                    if (StringUtils.isNotBlank(language)) {
                        languageIden = language;
                    } else {
                        languageIden = "en_US";
                    }
                    break;
            }
            Locale locale = LocaleUtils.toLocale(languageIden);
            return MESSAGE_SOURCE.getMessage(code, args, locale);
        } else {
            String language = ServletUtils.getRequest().getHeader(CONTENT_LANGUAGE);
            if (StringUtils.isNotBlank(language)) {
                Locale locale = LocaleUtils.toLocale(language);
                return MESSAGE_SOURCE.getMessage(code, args, locale);
            }
            return MESSAGE_SOURCE.getMessage(code, args, LocaleContextHolder.getLocale());
        }
    }


}
